//
//  XLRequestManager.m
//  MPTinyAppLearn
//
//  Created by xl on 2019/11/7.
//  Copyright © 2019 xl. All rights reserved.
//

#import "XLRequestManager.h"

@implementation XLRequestConfig

 
@end


@interface XLRequestManager()

@property (nonatomic, strong) NSMutableDictionary *reqMap;
@property (nonatomic, assign) int reqSequence;


@end

@implementation XLRequestManager

+ (XLRequestManager *)sharedInstance {
    static XLRequestManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [XLRequestManager new];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.reqMap = [[NSMutableDictionary alloc] init];
        self.reqSequence = 0;
    }
    return self;
}

//过滤请求
- (BOOL)filterRequest:(NSString *)requestUrl {
    @synchronized(self)
       {
           for (XLRequestConfig *reqConfig in self.reqMap.allValues) {
               if ([reqConfig.baseUrl isEqualToString:requestUrl]) {
                   return YES;
               }
           }
           return NO;
       }
}

- (int)getNextReqId
{
    @synchronized(self)
    {
        return self.reqSequence++;
    }
}

- (void)addReqConfig:(XLRequestConfig *)reqConfig
{
    @synchronized(self)
    {
        [self.reqMap setObject:reqConfig forKey:[NSNumber numberWithInt:reqConfig.reqId]];
//        XLNetLog(@"addReq,reqid=%d",reqConfig.reqId);
    }
}

- (void)removeReqConfig:(int)reqId {
    @synchronized(self)
       {
           [self.reqMap removeObjectForKey:[NSNumber numberWithInt:reqId]];
//           XLNetLog(@"removeReq,reqid=%d",seqid);
       }
}

//取消所有请求
- (void)removeAllRequest {
    @synchronized (self) {
           [self.reqMap enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
               XLRequestConfig *request=(XLRequestConfig*)obj;
               if (request.requestTask) {
                   [request.requestTask cancel];
               }
           }];
       }

}

- (void)cancelRequestWithReqIds:(NSArray *)seqIds
{
    @synchronized (self) {
        [seqIds enumerateObjectsUsingBlock:^(id  obj, NSUInteger idx, BOOL * stop) {
            XLRequestConfig *request=(XLRequestConfig*)obj;
            if (request.requestTask) {
                [request.requestTask cancel];
            }
            [self.reqMap removeObjectForKey:[NSNumber numberWithInt:request.reqId]];
        }];
    }
}
@end
